const reqTypes = {};

// 处理响应提示信息
function handleResponseMessage(pass, res, config, checkPass = true) {
  // 响应的提示消息默认是 message 字段，可以通过 messageKey 配置修改字段
  const responseMessage = res[config.messageKey || 'message'];
  let message = checkPass ? !pass && responseMessage : responseMessage;
  // 可以通过配置 message 修改接口成功和失败提示信息，如果是 false 将不提醒
  if (Array.isArray(config.message)) {
    message = pass ? config.message[0] : config.message[1];
  } else if (config.message !== void 0) {
    message = config.message;
  }
  return message;
}

/**
 * 分页式请求
 * @example { code: '0', data: { list: [], total: 0 }, message: '' }
 */
reqTypes.table = (res, config) => {
  const pass = res.code === (config.successCode || '0');
  const data = {
    list: res.data?.list || [],
    total: res.data?.total || res?.data?.list?.length || 0,
    pageNumber: config.params.pageNumber,
    pageSize: config.params.pageSize,
  };
  return {
    pass,
    data,
    message: handleResponseMessage(pass, res, config),
    onFormat: (format, isItemFormat) => {
      if (isItemFormat) return { ...data, list: data.list.map((item) => format(item)) };
      return format(data);
    },
  };
};

/**
 * 无分页式请求
 * @example { code: '0', list: [], message: '' }
 */
reqTypes.list = (res, config) => {
  const pass = res.code === (config.successCode || '0');
  const list = res.list || [];
  return {
    pass,
    data: list,
    message: handleResponseMessage(pass, res, config),
    onFormat: (format, isItemFormat) => {
      if (isItemFormat) return list.map((item) => format(item));
      return format(list);
    },
  };
};

/**
 * 单项式请求
 * @example { code: '0', data: {}, message: '' }
 */
reqTypes.profile = (res, config) => {
  const { defaultData = {} } = config;
  const pass = res.code === (config.successCode || '0');
  const data = !!res.data || res.data === false || res.data === 0 || res.data === '' ? res.data : defaultData;
  return {
    pass,
    data,
    message: handleResponseMessage(pass, res, config),
    onFormat: (format) => format(data),
  };
};

/**
 * 命令式请求
 * @example { code: '0', message: '' }
 */
reqTypes.command = (res, config) => {
  const pass = res.code === (config.successCode || '0');
  const msg = handleResponseMessage(pass, res, config, false);
  return { pass, message: msg };
};

export default reqTypes;
